
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ = db.command

// @ts-ignore
async function getPermissionByRoleId(roleId) {
    console.log("roleId===")
    console.log(roleId)
    //1.查询全部角色
    let rolePermission = await nw.db.findListByWhereJson({
        dbName:"rolePermission",
        whereJson:{roleId:roleId,deleted:0}
    })

    console.log("角色关系查询===")
    console.log(rolePermission)

    if (nw.util.isNull(rolePermission)||rolePermission.length===0){
        return new Promise<any[]>((resolve, _)=>resolve([]))
    }
    let permissionIds = rolePermission.map(item=>item.permissionId)

    let permissions = await nw.db.findListByWhereJson({
        dbName:"permission",
        whereJson:{
            _id:_.in(permissionIds),deleted:0
        }
    })
    console.log(permissions)
    return new Promise((resolve, _)=>resolve(permissions))
}

export default async function (ctx: FunctionContext) {
    let body = ctx.body
    /**
     * {
     *   "roleId": "122"
     * }
     */

    if (nw.util.isNull(body.roleId)){
        return fail("数据不合法")
    }

    //1.查询全部数据
    let allPermisssions = await nw.db.findListByWhereJson({
        dbName:"permission",
        whereJson:{deleted:0}
    })
    //2.查询只有该角色的权限
    let roleHasPermissions = await getPermissionByRoleId(body.roleId)

    //3.构建返回结果即可
    let result = {
        allPermisssions:allPermisssions,
        roleHasPermissions:roleHasPermissions
    }

    return ok(result,"查询成功")

}
